import json
import re
import time
from datetime import datetime
import requests
from bs4 import BeautifulSoup
from win10toast import ToastNotifier
import schedule


def get_url_info():
    url = 'https://indienova.com/gamedb/list/121/p/1'
    headers = {
        'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/90.0.4430.72 Safari/537.36 Edg/90.0.818.41'}
    res = requests.get(url, headers=headers).text
    return res

# 过滤有用数据
def check_epci_info(game_info_list):
    list_content = []
    for i in game_info_list:
        game_time = i['game_start'][0]
        start_time = str.strip(str.split(game_time, '-')[0])
        end_time = str.strip(str.split(game_time, '-')[1])
        try:
            start_time = datetime.strptime(start_time, "%Y/%m/%d")
            end_time = datetime.strptime(end_time, "%Y/%m/%d")
        except ValueError:
            # 日期非标准，跳过
            print('error:' + str(i))
            continue

        if start_time <= datetime.now() and end_time >= datetime.now():
            list_content.append(i)
    return list_content

# 解析获取网页数据
def parse_web_page(res):
    soup = BeautifulSoup(res, "html.parser")
    res.encode('UTF-8').decode('UTF-8')
    div_class = soup.find(name='div', attrs={"id": "portfolioList"})
    # print(div_class[0])
    game_name = div_class.find_all(name='div', attrs={"class": "col-xs-12 col-sm-6 col-md-4 user-game-list-item"})
    list_game = str(game_name).split('<div class="col-xs-12 col-sm-6 col-md-4 user-game-list-item">')
    game_info_list = []
    for i in list_game[1:]:
        dict_info = {}
        # print('----------------------------------------------------------------------------------')
        game = BeautifulSoup(i, "html.parser")
        game_all_info = game.find(name='h4')
        game_name_zh = game_all_info.find_all(name='a')
        game_name_en = game_all_info.find_all(name='small')
        game_name_zh = re.findall(r'>(.+?)<', str(game_name_zh))
        game_name_en = re.findall(r'>(.+?)<', str(game_name_en))
        # print(game_name_zh, game_name_en)
        game_start_end = game.find(name='p', attrs={"class": "intro"})
        game_start_end_new = game_start_end.find_all(name='span')
        game_edit_time = game.find(name='p', attrs={"class": "text-date"})
        game_edit_time_new = game_edit_time.find_all(name='small')
        game_edit_time_new = str(game_edit_time_new).replace(" ", "").replace("\n", " ")

        game_start_end_new = re.findall(r'>(.+?)<', str(game_start_end_new))
        game_edit_time_new = re.findall(r'>(.+?)<', str(game_edit_time_new))
        dict_info["game_zh"] = game_name_zh
        dict_info["game_en"] = game_name_en
        dict_info["game_start"] = game_start_end_new
        dict_info["game_time"] = game_edit_time_new
        game_info_list.append(dict_info)

    # print(game_start_end_new,game_edit_time_new)
    return game_info_list


# windows 通知显示
def notify_on_windows(title, text):
    # 创建一个ToastNotifier对象
    toaster = ToastNotifier()
    toaster.show_toast(
        title=title,
        msg=text,
        icon_path='./epic.ico',  # 你可以提供一个.ico文件路径来自定义图标
        duration=5,  # 通知显示的时间（秒）
        threaded=True  # 是否允许主线程继续运行
    )
    # 等待所有通知弹出
    while toaster.notification_active():
        pass

# 获取数据发送通知
def process_date():
    res = get_url_info()
    game_info_list = parse_web_page(res)
    list_content = check_epci_info(game_info_list)
    text = ''
    if bool(list_content):
        for i in list_content:
            text = text + '游戏名称:《' + i['game_zh'][0] + '》,领取时间:' + i['game_start'][0] + ';\n'
    notify_on_windows("Epic免费游戏通知", text)

if __name__ == '__main__':
    notify_on_windows("启动成功！", '程序运行中。。。')
    #process_date()
    schedule.every().day.at("15:03").do(process_date)
    while True:
        schedule.run_pending()
        time.sleep(1)  # 每秒检查一次是否有任务需要执行
